package com.itheima.service.syslog.impl;

import com.github.pagehelper.PageHelper;
import com.itheima.domain.SysLog;
import com.itheima.factory.MapperFactory;
import com.itheima.mapper.syslog.SysLogMapper;
import com.itheima.service.syslog.SysLogService;
import com.itheima.utils.TransactionUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.ByteArrayOutputStream;
import java.util.List;

public class SysLogServiceImpl implements SysLogService {

    SqlSession sqlSession;

    /**
     * 查询日志
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<SysLog> findAll(String pageNum, String pageSize) {
        try {
            //获取sqlSession对象
            sqlSession = MapperFactory.getSqlSession();
            //获取代理对象
            SysLogMapper mapper = sqlSession.getMapper(SysLogMapper.class);
            //设置分页参数：当前页面  每页显示的条目数
            int pageN = 1;
            int pageS = 5;
            if (StringUtils.isNotBlank(pageNum)){
                pageN = Integer.parseInt(pageNum);
            }
            if (StringUtils.isNotBlank(pageSize)){
                pageS = Integer.parseInt(pageSize);
            }
            //分页插件调用方法
            PageHelper.startPage(pageN,pageS);
            //调用持久层方法
            List<SysLog> list = mapper.findAll();
            return list;
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            //释放资源
            TransactionUtil.close(sqlSession);
        }
    }

    /**
     * 模糊查询
     * @param pageNum
     * @param pageSize
     * @param time
     * @return
     */
    @Override
    public List<SysLog> findAll(String pageNum, String pageSize, String time) {
        try {
            //获取sqlSession对象
            sqlSession = MapperFactory.getSqlSession();
            //获取代理对象
            SysLogMapper mapper = sqlSession.getMapper(SysLogMapper.class);
            //设置分页参数：当前页面  每页显示的条目数
            int pageN = 1;
            int pageS = 5;
            if (StringUtils.isNotBlank(pageNum)){
                pageN = Integer.parseInt(pageNum);
            }
            if (StringUtils.isNotBlank(pageSize)){
                pageS = Integer.parseInt(pageSize);
            }
            //分页插件调用方法
            PageHelper.startPage(pageN,pageS);
            //调用持久层方法
            List<SysLog> list = mapper.findByTime(time);
            return list;
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            //释放资源
            TransactionUtil.close(sqlSession);
        }
    }

    /**
     * 根据id 删除日志
     * @param ids
     * @return
     */
    @Override
    public Boolean deleteByIds(String ids) {
        Boolean flag = false;
        try {
            //获取sqlSession对象
            sqlSession = MapperFactory.getSqlSession();
            //获取代理对象
            SysLogMapper mapper = sqlSession.getMapper(SysLogMapper.class);
            //对ID处理
            String[] id = ids.split(",");
            //调用持久层方法
            mapper.deleteByIds(id);
            //成功，提交事务
            TransactionUtil.commit(sqlSession);
            flag = true;
        }catch (Exception e){
            //失败，回滚事务
            TransactionUtil.rollback(sqlSession);
            e.printStackTrace();
        }finally {
            //释放资源
            TransactionUtil.close(sqlSession);
            return flag;
        }
    }


    @Override
    public void save(SysLog sysLog) {
        try {
            if(sysLog == null) return;
            //获取sqlSession对象
            sqlSession = MapperFactory.getSqlSession();
            //获取代理对象
            SysLogMapper mapper = sqlSession.getMapper(SysLogMapper.class);

            //调用持久层方法
            mapper.save(sysLog);
            TransactionUtil.commit(sqlSession);
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            //释放资源
            TransactionUtil.close(sqlSession);
        }
    }

    /**
     * 下载报表
     * @return
     */
    @Override
    public ByteArrayOutputStream getReport() throws Exception{
        List<SysLog> sysLogList = null;
        try {
            //获取sqlSession对象
            sqlSession = MapperFactory.getSqlSession();
            //获取代理对象
            SysLogMapper mapper = sqlSession.getMapper(SysLogMapper.class);
            sysLogList = mapper.findAll();
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            //释放资源
            TransactionUtil.close(sqlSession);
        }

        //1.获取到对应的Excel文件，工作簿文件
        Workbook wb = new XSSFWorkbook();

        //2.创建工作表
        Sheet s = wb.createSheet("系统日志");

        //设置通用配置
//        s.setColumnWidth(4,100);
        CellStyle cs_field = wb.createCellStyle();
        cs_field.setAlignment(HorizontalAlignment.CENTER);
        cs_field.setBorderTop(BorderStyle.THIN);
        cs_field.setBorderBottom(BorderStyle.THIN);
        cs_field.setBorderLeft(BorderStyle.THIN);
        cs_field.setBorderRight(BorderStyle.THIN);

        //制作标题
        s.addMergedRegion(new CellRangeAddress(1, 1, 1, 7));

        Row row_1 = s.createRow(1);
        Cell cell_1_1 = row_1.createCell(1);
        cell_1_1.setCellValue("系统日志");

        //创建一个样式
        CellStyle cs_title = wb.createCellStyle();
        cs_title.setAlignment(HorizontalAlignment.CENTER);
        cs_title.setVerticalAlignment(VerticalAlignment.CENTER);
        cell_1_1.setCellStyle(cs_title);

        //制作表头
        String[] fields = {"日志ID", "访问时间", "用户名", "用户IP", "访问路径",
                "操作时间", "执行方法"};
        Row row_2 = s.createRow(2);

        for (int i = 0; i < fields.length; i++) {
            Cell cell_2_temp = row_2.createCell(1 + i); //++
            cell_2_temp.setCellValue(fields[i]);    //++
            cell_2_temp.setCellStyle(cs_field);
        }
        //设置时间列宽
        s.setColumnWidth(2, 5000);

        //制作数据区
        int row_index = 0;
        for (SysLog log : sysLogList) {
            int cell_index = 0;
            Row row_temp = s.createRow(3 + row_index++);

            Cell cell_data_1 = row_temp.createCell(1 + cell_index++);
            cell_data_1.setCellValue(log.getId());    //++
            cell_data_1.setCellStyle(cs_field);

            Cell cell_data_2 = row_temp.createCell(1 + cell_index++);
            cell_data_2.setCellValue(log.getVisitTimeStr());    //++
            cell_data_2.setCellStyle(cs_field);

            Cell cell_data_3 = row_temp.createCell(1 + cell_index++);
            cell_data_3.setCellValue(log.getUsername());    //++
            cell_data_3.setCellStyle(cs_field);

            Cell cell_data_4 = row_temp.createCell(1 + cell_index++);
            cell_data_4.setCellValue(log.getIp());    //++
            cell_data_4.setCellStyle(cs_field);

            Cell cell_data_5 = row_temp.createCell(1 + cell_index++);
            cell_data_5.setCellValue(log.getUrl());    //++
            cell_data_5.setCellStyle(cs_field);

            Cell cell_data_6 = row_temp.createCell(1 + cell_index++);
            cell_data_6.setCellValue(log.getExecutionTime()+"毫秒");    //++
            cell_data_6.setCellStyle(cs_field);

            Cell cell_data_7 = row_temp.createCell(1 + cell_index++);
            cell_data_7.setCellValue(log.getMethod());    //++
            cell_data_7.setCellStyle(cs_field);

        }

        //将内存中的workbook数据写入到流中
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        wb.write(os);
        wb.close();
        return os;
    }

}
